const router = require('koa-router')()
const { ENV } = require('../utils/env')
const packageInfo = require('../../package.json')
const UserModel = require('../model/user')
const { cacheGet, cacheSet } = require('../cache/index')

// 测试数据库连接
router.get('/ping', async ctx => {
  // 测试 mongodb 连接
  let mongodbConn
  try {
    mongodbConn = true
    await UserModel.findOne()
  } catch (ex) {
    mongodbConn = false
  }

  // 测试 redis 连接
  cacheSet('name', 'admin-server OK - by redis')
  const redisTestVal = await cacheGet('name')

  ctx.body = {
    errno: 0,
    data: {
      name: 'admin-server',
      version: packageInfo.version,
      ENV,
      mongodbConn,
      redisConn: redisTestVal != null
    }
  }
})

module.exports = router
